package com.huaxin.hxcloud.activity;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.Org;
import com.huaxin.common.Entity.StationDTO;
import com.huaxin.common.utils.Util;
import com.huaxin.common.view.roundedimageview.RoundedImageView;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.work.HxStationInfoActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindColor;
import butterknife.BindView;

/**
 * Created by Administrator on 2016/9/23.
 */
public class StationMapActivity extends BaseActivity implements BaiduMap.OnMapLoadedCallback, SensorEventListener {

    private static final String TAG = "StationMapActivity";
    @BindView(R.id.more)
    ImageView        more;
    @BindView(R.id.toolbar)
    Toolbar          toolbar;
    @BindView(R.id.map)
    MapView          map;
    @BindView(R.id.img)
    RoundedImageView img;
    @BindView(R.id.stationName)
    TextView         stationName;
    @BindView(R.id.buildAddress)
    TextView         buildAddress;
    @BindView(R.id.ownerName)
    TextView         ownerName;
    @BindView(R.id.phone)
    TextView         phone;
    @BindView(R.id.state)
    TextView         state;
    @BindView(R.id.tv_total)
    TextView         tvTotal;
    @BindView(R.id.tv_uninitialized)
    TextView         tvUninitialized;
    @BindView(R.id.tv_out_time)
    TextView         tvOutTime;
    @BindView(R.id.tv_error)
    TextView         tvError;
    @BindView(R.id.ll_org)
    LinearLayout     llOrg;
    @BindView(R.id.rl_station)
    RelativeLayout   rlStation;


    private ArrayList<StationDTO> stationList;
    private Org                   curOrg;
    private BaiduMap              mBaiduMap;

    private StationDTO selStation;
    private Marker     selMarker;
    @BindColor(R.color.state_green)
    int static_normal;
    @BindColor(R.color.state_orange)
    int static_bug;
    @BindColor(R.color.state_gray)
    int static_out;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private BitmapDescriptor                     mCurrentMarker;
    private MyLocationConfiguration              mConfiguration;
    private LocationClient                       mLocClient;

    private SensorManager mSensorManager;
    private List<Overlay> mOverlays=new ArrayList<>();


    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_STATION_LIST) && extras.containsKey(Constants.IK_ORG)) {
            stationList = extras.getParcelableArrayList(Constants.IK_STATION_LIST);
            curOrg = extras.getParcelable(Constants.IK_ORG);
        } else {
            finish();
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_station_map;
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        toolbar.setTitle(curOrg.getOrgName());
        mBaiduMap = map.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setBuildingsEnabled(false);
        map.removeViewAt(2);
        View child = map.getChildAt(1);
        if (child instanceof ImageView || child instanceof ZoomControls) {
            child.setVisibility(View.GONE);
        }
        initMark();
        initLocation();

        mBaiduMap.setOnMapLoadedCallback(this);
    }

    private void initMark() {
        if (stationList.isEmpty()) {
            return;
        }
        List<OverlayOptions> optionList = new ArrayList<>();
        List<LatLng> points = new ArrayList<LatLng>();
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (StationDTO station : stationList) {
            if (!(station.getLat() == 0.0) || !(station.getLng() == 0.0)) {

                Log.d(TAG, "initMark: ---->" + station.toString());
                Bundle bundle = new Bundle();
                bundle.putParcelable(Constants.IK_STATION, station);
                LatLng point = new LatLng(station.getLat(), station.getLng());
                points.add(point);
                builder = builder.include(point);
                MarkerOptions option = new MarkerOptions()
                        .position(point)
                        .icon(getBDescriptor(station.getStationState(), false))
                        .extraInfo(bundle);
                //                    .animateType(MarkerOptions.MarkerAnimateType.drop);
                optionList.add(option);
            }

        }
        mOverlays = mBaiduMap.addOverlays(optionList);

        //        LatLngBounds latlngBounds = builder.build();
        //        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(latlngBounds);
        //        mBaiduMap.animateMapStatus(u);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (!Util.checkNull(selMarker)) {
                    selStation = selMarker.getExtraInfo().getParcelable(Constants
                            .IK_STATION);
                    selMarker.setIcon(getBDescriptor(selStation.getStationState(), false));
                }
                selMarker = marker;
                selStation = selMarker.getExtraInfo().getParcelable(Constants
                        .IK_STATION);
                selMarker.setIcon(getBDescriptor(selStation.getStationState(), true));

                updateStationInfo(selMarker);
                return true;
            }
        });

        //        });
    }

    /**
     * @desc 初始定位
     * @author songxf
     * created at 2017/7/12 16:03
     */
    private void initLocation() {
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(new MyLocationListenner());
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mConfiguration = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
        mBaiduMap.setMyLocationConfigeration(mConfiguration);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于
        mLocClient.setLocOption(option);
        mLocClient.start();
        //  mBaiduMap.
    }

    /**
     * 定位SDK监听函数
     */
    private int    mCurrentDirection = 0;
    private double mCurrentLat       = 0.0;
    private double mCurrentLon       = 0.0;
    private float          mCurrentAccracy;
    private MyLocationData locData;
    boolean isFirstLoc = true; // 是否首次定位
    private Double lastX = 0.0;

    /**
     * @desc 罗盘 旋转改变
     * @author songxf
     * created at 2017/7/12 16:22
     */
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mBaiduMap == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(6.5f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }
    }

    @Override
    public void initData() {
        updateOrgInfo();
    }

    private int[] countNum() {
        int[] countNum = new int[5];
        for (StationDTO station : stationList) {
            if (station.getStationState() < 4) {
                countNum[station.getStationState()]++;
            }
            countNum[4]++;
        }
        return countNum;

    }

    private void updateOrgInfo() {
        int[] count = countNum();
        loadText("运维总数：", tvTotal, String.valueOf(count[4]));
        loadText("未初始化：", tvUninitialized, String.valueOf(count[3]));
        loadText("故障总数：", tvError, String.valueOf(count[2]));
        loadText("超时台数：", tvOutTime, String.valueOf(count[1]));
    }

    private void updateStationInfo(final Marker selMarker) {
        View v = mInflater.inflate(R.layout.info_station, null);
        TextView tvStationName = (TextView) v.findViewById(R.id.tv_station_name);
        TextView tvStationAddress = (TextView) v.findViewById(R.id.tv_station_address);
        loadText(tvStationName, selStation.getStationName());
        loadText("地址：", tvStationAddress, selStation.getAddress(), "暂无");
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HxStationInfoActivity.start(StationMapActivity.this, selStation.getStationCode());
            }
        });
        final LatLng ll = selMarker.getPosition();
        InfoWindow mInfoWindow = new InfoWindow(v, ll, -47);
        mBaiduMap.showInfoWindow(mInfoWindow);
        //点击地图其他区域 隐藏infowindow
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        //        rlStation.setVisibility(View.VISIBLE);
        //        setStateText(state, selStation.getStationState());
        //        loadNetImg(img, selStation.getStationImg());
        //        loadText(stationName, selStation.getStationName());
        //        loadText("地址：", buildAddress, selStation.getAddress(), "暂无");
        //        loadText("负责人：", ownerName, selStation.getContactPerson(), "暂无");
        //        loadText(phone, selStation.getContactPhone());
    }

    private void setStateText(TextView textView, int state) {
        //站点状态 0:正常，1：通讯超时，2、故障，3、待初始化
        textView.setVisibility(View.VISIBLE);
        switch (state) {
            case 0:
                textView.setText("正常");
                textView.setTextColor(static_normal);
                textView.setBackgroundResource(R.drawable.bg_normal_green);
                break;
            case 1:
                textView.setText("超时");
                textView.setTextColor(static_bug);
                textView.setBackgroundResource(R.drawable.bg_bug);
                break;
            case 2:
                textView.setText("故障");
                textView.setTextColor(static_bug);
                textView.setBackgroundResource(R.drawable.bg_bug);
                break;
            case 3:
                textView.setText("待初始化");
                textView.setTextColor(static_bug);
                textView.setBackgroundResource(R.drawable.bg_bug);

                break;
            default:
                textView.setVisibility(View.GONE);
                break;
        }
    }

    BitmapDescriptor getBDescriptor(int state, boolean selected) {
        BitmapDescriptor bitmapDescriptor;
        switch (state) {
            case 0:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(
                        selected ? R.drawable.icon_normal_f : R.drawable.icon_normal);
                break;
            case 1:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(
                        selected ? R.drawable.icon_outtime_f : R.drawable.icon_outtime);
                break;
            case 2:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(
                        selected ? R.drawable.icon_stop_f : R.drawable.icon_stop);

                break;
            case 3:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(
                        selected ? R.drawable.icon_un_init_f : R.drawable.icon_un_init);

                break;
            default:
                bitmapDescriptor = BitmapDescriptorFactory.fromResource(
                        selected ? R.drawable.icon_normal_f : R.drawable.icon_normal);

                break;
        }
        return bitmapDescriptor;
    }


    public static void start(Activity context, Org curOrg, ArrayList<StationDTO> stationList) {
        Intent intent = new Intent(context, StationMapActivity.class);
        intent.putExtra(Constants.IK_ORG, curOrg);
        intent.putExtra(Constants.IK_STATION_LIST, stationList);
        context.startActivityForResult(intent, Constants.RET_SELECT_ORG);
    }


    @Override
    protected void onResume() {
        map.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
        super.onResume();

    }

    @Override
    protected void onPause() {
        map.onPause();
        super.onPause();

    }

    /**
     * @desc 地图绘制完成回调
     * @author songxf
     * created at 2017/7/13 15:04
     */
    @Override
    public void onMapLoaded() {
        final LatLngBounds.Builder builder = new LatLngBounds.Builder();
        if (!(mOverlays.size() == 0)) {
            for (Overlay overlay : mOverlays) {
                builder.include(((Marker) overlay).getPosition());
            }
            //设置多个覆盖物，地图的缩放比例
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(builder.build().getCenter(), 6.5f));
        }
    }


    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        map.onDestroy();
        map = null;
        super.onDestroy();
    }

}
